import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { authApi } from '@/api/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/pages/Home.vue')
    },
    {
      path: '/my-exams',
      name: 'MyExams',
      component: () => import('@/pages/MyExams.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/my-exam-records',
      name: 'MyExamRecords',
      component: () => import('@/pages/MyExamRecords.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/ai',
      name: 'AIHome',
      component: () => import('@/pages/AIPage.vue'),
      meta: { requiresAuth: true }
    },

    {
      path: '/learning-analytics',
      name: 'LearningAnalytics',
      component: () => import('@/pages/LearningAnalytics.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/notes',
      name: 'Notes',
      component: () => import('@/pages/Notes.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/pages/Login.vue'),
      beforeEnter: (to, from, next) => {
        const authStore = useAuthStore()
        authStore.initAuth()
        if (authStore.isLoggedIn) {
          next('/courses') // 已登录用户重定向到课程页
        } else {
          next()
        }
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/pages/Register.vue'),
      beforeEnter: (to, from, next) => {
        const authStore = useAuthStore()
        authStore.initAuth()
        if (authStore.isLoggedIn) {
          next('/courses') // 已登录用户重定向到课程页
        } else {
          next()
        }
      }
    },
    {
      path: '/courses',
      name: 'Courses',
      component: () => import('@/pages/CoursesEnhanced.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/courses/:id',
      name: 'CourseDetail',
      component: () => import('@/pages/CourseDetailEnhanced.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/courses/:id/qna',
      name: 'CourseCommunity',
      component: () => import('@/pages/course/Community.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/posts/:id',
      name: 'PostDetail',
      component: () => import('@/pages/course/PostDetail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('@/pages/Profile.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/health',
      name: 'Health',
      component: () => import('@/pages/Health.vue')
    },
    // Teacher Routes
    {
      path: '/teacher',
      redirect: '/teacher/dashboard',
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/dashboard',
      name: 'TeacherDashboard',
      component: () => import('@/pages/teacher/Dashboard.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/courses',
      name: 'TeacherCourses',
      component: () => import('@/pages/teacher/Courses.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/courses/create',
      name: 'CreateCourse',
      component: () => import('@/pages/teacher/CourseEditor.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/courses/:id/edit',
      name: 'EditCourse',
      component: () => import('@/pages/teacher/CourseEditor.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/question-bank',
      name: 'QuestionBank',
      component: () => import('@/pages/teacher/QuestionBank.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
      path: '/teacher/exam-management',
      name: 'ExamManagement',
      component: () => import('@/pages/teacher/ExamManagement.vue'),
      meta: { requiresAuth: true, requiresTeacher: true }
    },
    // Exam and Certificate Routes

    {
      path: '/exam-result/:id',
      name: 'ExamResult',
      component: () => import('@/pages/ExamResult.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/my-certificates',
      name: 'MyCertificates',
      component: () => import('@/pages/MyCertificates.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/certificates',
      redirect: '/my-certificates'
    },
    {
      path: '/exam/:id',
      name: 'ExamTaking',
      component: () => import('@/pages/ExamTaking.vue'),
      meta: { requiresAuth: true }
    },
    // Player Routes
    {
      path: '/player/video',
      name: 'VideoPlayer',
      component: () => import('@/pages/player/VideoPlayer.vue')
    },
    {
      path: '/player/document',
      name: 'DocumentPlayer',
      component: () => import('@/pages/player/DocumentPlayer.vue')
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态
  const authInitialized = authStore.initAuth()
  
  console.log(`🛣️ 路由守卫: ${from.path || '/'} -> ${to.path}`)
  console.log(`🔐 认证状态: ${authStore.isLoggedIn ? '已登录' : '未登录'}`)
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    console.log('❌ 需要登录，重定向到登录页')
    // 只有当不是从登录页跳转时才显示提示
    if (from.path !== '/login' && from.path !== '/register') {
      ElMessage({
        type: 'info',
        message: '欢迎来到启航！请先登录或注册账户以享受完整的学习体验',
        duration: 4000,
        showClose: true
      })
    }
    next('/login')
    return
  }
  
  // 检查是否需要教师权限
  if (to.meta.requiresTeacher && authStore.isLoggedIn) {
    try {
      // 获取用户信息（如果还没有）
      let userInfo = authStore.user
      if (!userInfo) {
        console.log('🔄 获取用户信息...')
        userInfo = await authApi.me()
        authStore.user = userInfo // 更新store中的用户信息
      }
      
      const userRole = userInfo?.role
      if (userRole !== 'TEACHER' && userRole !== 'ADMIN') {
        console.log(`❌ 权限不足: ${userRole}`)
        ElMessage.error('您没有权限访问教师功能')
        next('/courses')
        return
      }
    } catch (error) {
      console.error('Failed to check teacher permission:', error)
      ElMessage.error('验证用户权限失败，请重新登录')
      authStore.logout()
      next('/login')
      return
    }
  }
  
  console.log('✅ 路由守卫通过')
  next()
})

export default router